<template>
  <div class="common-container">
    <goodDetail :product="productDetail"  @buy="handleBuy" @collect="handleCollect" />
  </div>
</template>

<script lang="ts" setup>
import goodDetail from './components/details.vue';
import { onMounted, ref, watch } from 'vue';
import { getDetail } from "@/api/test";
import { useRoute } from 'vue-router';
const route = useRoute();
const id = ref();
const productDetail = ref({
  name: '',
  max_price: 0,
  description: '',
  spec_list: [],
  detail_images: []
});

// 这个函数负责检查是否有预加载的商品数据
const checkPreloadedData = () => {
  // 检查是否有预加载的商品数据
  console.log("99999999999",(window as any).__INITIAL_PRODUCT__)
  return true
}

const getDetailData = async () => {
  id.value = route.query.id
  // if (!id.value) return
  console.log((window as any).__INITIAL_PRODUCT__ && !productDetail.value)
  // 如果有预加载数据就直接使用
  
  if ((window as any).__INITIAL_PRODUCT__) {
    // 可以直接使用预加载数据或者仍然请求完整数据
    // 这里选择仍然请求以获取完整数据
    // const res = await getDetail(id.value)
    // productDetail.value = res.result
    console.log("888888",(window as any).__INITIAL_PRODUCT__.productdetails)
    // // productDetail.value.images = res.result.images
    productDetail.value = (window as any).__INITIAL_PRODUCT__.productdetails

  } else {
    // 正常请求数据
    const res = await getDetail(id.value)

    productDetail.value = res.result
    console.log("1000",productDetail.value)
    // 确保 productDetail 有 specs 属性
    if (!productDetail.value.specs) {
      productDetail.value.specs = []
    }
    
    // productDetail.value.images = res.result.images
  }
}
// 监听路由变化
watch(
  () => [route.query.id, route.params.id],
  () => {
    // 仅当ID变化时重新获取数据
    const newId = route.query.id || route.params.id
    if (newId && newId !== id.value) {
      id.value = newId
      console.log(id.value)
      getDetailData()
    }
  }
)
onMounted(() => {
  // 初始化商品详情
  // ...
  checkPreloadedData()
  getDetailData()
});
const handleBuy = (product: any) => {
  console.log('购买商品:', product);
};

const handleCollect = (product: any) => {
  console.log('收藏商品:', product);
};
</script>

<style scoped>
/* 组件样式 */
</style>